var CDN_INFO = {
    ACCESS_KEY: 'bd8LY9ZjlVrIlRKT0BGCIZdv0L_vY9on-adaq7z3',
    SECRET_KEY: 'UShxqdbs-REiii2LFXhkf9XOzQpZsSgu1YrfBEUR'
};

module.exports = function upload2Cdn(uploads, fn, needRemoveFirst) {
    var cdn = require("qiniu"),
        depolyInfo = require("../../deploy-conf.json");

    cdn.conf.ACCESS_KEY = CDN_INFO.ACCESS_KEY;
    cdn.conf.SECRET_KEY = CDN_INFO.SECRET_KEY;

    var file = uploads.shift(),
        extra = new cdn.io.PutExtra(),
        uptoken = new cdn.rs.PutPolicy(depolyInfo.cdn || "fingerplus").token(),
        filename = "";

    if (file) {
        filename = file.filename;
        if (filename[0] == "/") {
            filename = filename.slice(1)
        }

        if (needRemoveFirst) {
            var client = new cdn.rs.Client();
            client.remove(depolyInfo.cdn, filename, function (err, ret) {
                if (err) {
                    console.log("some error happend:");
                    console.log(err);
                }

                cdn.io.putFile(uptoken, filename, file.path, extra, function (err) {
                    if (err) {
                        console.log(filename + " error!".red);
                        console.log(err);
                        process.exit(0);
                    } else {
                        console.log(filename + " complete..");
                        upload2Cdn(uploads, fn);
                    }
                });
            });
        } else {
            cdn.io.putFile(uptoken, filename, file.path, extra, function (err) {
                if (err) {
                    console.log(filename + " error!".red);
                    console.log(err);
                    process.exit(0);
                } else {
                    console.log(filename + " complete..");
                    upload2Cdn(uploads, fn);
                }
            });
        }
    } else {
        fn();
    }
};